/*
 * ChatServer.java
 *
 * This program demonstrate the use of Socket and serverSocket Socket classes in
 * networking Application.
 *
 * Copyright (c) 2007 Aptech Software Limited. All Rights Reserved.
 */
package demo.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author Vincent
 */
public class ChatServer extends javax.swing.JFrame {

    /**
     * Creates new form ChatServer
     */
    public ChatServer() {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (InstantiationException ex) {
            ex.printStackTrace();
        } catch (UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        }

        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
     * content of this method is always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnStartServer = new javax.swing.JButton();
        lblServerStatus = new javax.swing.JLabel();
        scpClientStatus = new javax.swing.JScrollPane();
        txaClientStatus = new javax.swing.JTextArea();
        scpClient = new javax.swing.JScrollPane();
        lstClient = new javax.swing.JList();
        pnlBroadCastMessage = new javax.swing.JPanel();
        lblMessage = new javax.swing.JLabel();
        txtMessage = new javax.swing.JTextField();
        btnBroadCastMessage = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Chat Server");
        setResizable(false);

        btnStartServer.setText("Start Server");
        btnStartServer.setPreferredSize(new java.awt.Dimension(150, 23));
        btnStartServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartServerActionPerformed(evt);
            }
        });

        lblServerStatus.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblServerStatus.setText("Loggined");

        scpClientStatus.setPreferredSize(new java.awt.Dimension(300, 150));

        txaClientStatus.setEditable(false);
        txaClientStatus.setColumns(20);
        txaClientStatus.setRows(5);
        scpClientStatus.setViewportView(txaClientStatus);

        scpClient.setPreferredSize(new java.awt.Dimension(130, 150));

        lstClient.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstClient.setEnabled(false);
        scpClient.setViewportView(lstClient);

        pnlBroadCastMessage.setPreferredSize(new java.awt.Dimension(430, 50));
        pnlBroadCastMessage.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 15));

        lblMessage.setText("Message:");
        lblMessage.setPreferredSize(new java.awt.Dimension(70, 20));
        pnlBroadCastMessage.add(lblMessage);

        txtMessage.setPreferredSize(new java.awt.Dimension(200, 20));
        pnlBroadCastMessage.add(txtMessage);

        btnBroadCastMessage.setText("Send");
        btnBroadCastMessage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBroadCastMessageActionPerformed(evt);
            }
        });
        pnlBroadCastMessage.add(btnBroadCastMessage);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(53, 53, 53)
                .add(btnStartServer, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(lblServerStatus)
                .add(53, 53, 53))
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(scpClientStatus, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 292, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(scpClient, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .add(7, 7, 7)
                .add(pnlBroadCastMessage, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(5, 5, 5)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnStartServer, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(lblServerStatus))
                .add(11, 11, 11)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(scpClientStatus, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE)
                    .add(scpClient, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(pnlBroadCastMessage, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 50, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        setSize(new java.awt.Dimension(486, 326));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void btnBroadCastMessageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBroadCastMessageActionPerformed
// TODO add your handling code here:
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                String strMessage;
                strMessage = txtMessage.getText();
                ps.println(strMessage);
                txtMessage.setText("");
            }
        });
    }//GEN-LAST:event_btnBroadCastMessageActionPerformed

    private void btnStartServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartServerActionPerformed
        blnServerStarted = true;
        btnStartServer.setEnabled(false);
        (new ServerThread()).start();
    }//GEN-LAST:event_btnStartServerActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ChatServer().setVisible(true);
            }
        });
    }

    class ServerThread extends Thread {

        String strMsg = "";
        boolean blnSignIn;
        boolean blnConnect;
        int index = 0;

        public ServerThread() {
            try {
                serverSocket = new ServerSocket(2759);
                btnStartServer.setText("Port : " + Integer.toString(serverSocket.getLocalPort()));
            } catch (IOException ex) {
                ex.printStackTrace();

            }
        }

        @Override
        public void run() {
            while (true) {
                if (!blnConnect) {
                    try {
                        clientSocket = serverSocket.accept();
                        ps = new PrintStream(clientSocket.getOutputStream());
                        br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        blnConnect = true;
                        blnSignIn = false;
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "Error occured. Contact Vendor", "Warning !", JOptionPane.WARNING_MESSAGE);
                    }
                }

                try {
                    if ((strMsg = br.readLine()) != null) {
                        if (!blnSignIn) {
                            vecUsers.add(strMsg);
                            lstClient.setListData(vecUsers);
                            blnSignIn = true;
                        } else {
                            txaClientStatus.append(strMsg + "\n");
                        }
                    }
                } catch (Exception ex) {
                    blnConnect = false;
                }

            }
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBroadCastMessage;
    private javax.swing.JButton btnStartServer;
    private javax.swing.JLabel lblMessage;
    private javax.swing.JLabel lblServerStatus;
    private javax.swing.JList lstClient;
    private javax.swing.JPanel pnlBroadCastMessage;
    private javax.swing.JScrollPane scpClient;
    private javax.swing.JScrollPane scpClientStatus;
    private javax.swing.JTextArea txaClientStatus;
    private javax.swing.JTextField txtMessage;
    // End of variables declaration//GEN-END:variables
    static ServerSocket serverSocket;
    Socket clientSocket;
    BufferedReader br;
    PrintStream ps;
    String strMessage = "";
    static boolean blnServerStarted = false;
    String s = "";
    Vector vecUsers = new Vector();
}
